package com.yeqian.attachment.service.impl;

import cn.hutool.core.io.file.FileNameUtil;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yeqian.attachment.service.AttachmentService;
import com.yeqian.attachment.configuration.AttachmentConfigProperties;
import com.yeqian.attachment.config.FileUploadConfig;
import com.yeqian.attachment.entity.AttachmentFile;
import com.yeqian.attachment.mapper.AttachmentMapper;
import com.yeqian.attachment.utils.FileUploadUtil;
import com.yeqian.user.service.UserSessionService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Set;

/**
 * 本地附件 服务
 */
@Slf4j
public class LocalAttachmentServiceImpl extends ServiceImpl<AttachmentMapper, AttachmentFile> implements AttachmentService {

    @Resource
    private AttachmentConfigProperties attachmentConfigProperties;

    @Resource
    private UserSessionService userSessionService;
    @Resource
    private FileUploadConfig fileUploadConfig;

    /**
     * 文件上传
     *
     * @param file
     * @param uploadPath
     * @param fileType
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttachmentFile uploadFile(MultipartFile file, String uploadPath, String fileType) {
        String currentUserId = userSessionService.getCurrentUserId();
        return this.uploadFile(file, uploadPath, fileType, currentUserId);
    }

    private AttachmentFile uploadFile(MultipartFile file, String uploadPath, String fileType, String userId) {
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        fileType = FileNameUtil.extName(fileName);
        Set<String> allowFileExt = this.fileUploadConfig.getAllowFileExt();
        FileUploadUtil.checkFileExt(fileType, allowFileExt);
        String relativepath = uploadPath + "\\" + fileName;
        String path = attachmentConfigProperties.getUpload() + relativepath;
        File dest = new File(path);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException ex) {
            log.error("上传文件失败:", ex);
        }
        return this.saveSAttachmentFile(file, path, relativepath, fileType, userId);
    }
}
